package com.longtxt.powerband.util

import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment

class PermissionHelper: Fragment() {

    fun request(permission: String) {
        requestPermissions(arrayOf(permission), 1)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        fragmentManager?.beginTransaction()?.remove(this)?.commit()
    }

    companion object {
        fun requestPermission(context: Context, permission: String) {
            if (context is Activity) {
                ActivityCompat.requestPermissions(context, arrayOf(permission), 1)
            } else {
                val fragmentMgr = (context as AppCompatActivity).supportFragmentManager
                val permissionHelper = PermissionHelper()
                permissionHelper.request(permission)
            }
        }
    }
}